

//
//  BAImageNode.m
//  BabyAlbum
//
//  Created by master on 17/2/15.
//  Copyright © 2017年 master. All rights reserved.
//

#import "BAResourceNode.h"


@implementation BAResourceNode
{
    ASImageNode *_imageNode;
    ASImageNode *_deleteNode;
    ASImageNode *_playNode;
}

- (id)initWithImage:(UIImage *)image editMode:(BOOL)editMode
{
    self = [super init];
    if (self != nil) {
        _imageNode = [[ASImageNode alloc] init];
        _imageNode.image = [image thumbImageForSize:CGSizeMake(200, 200)];
        [self addSubnode:_imageNode];
        
        _deleteNode = [[ASImageNode alloc] init];
        _deleteNode.image = [UIImage imageNamed:@"delete"];
        _deleteNode.hidden = !editMode;
        [_deleteNode addTarget:self action:@selector(deleteAction) forControlEvents:ASControlNodeEventTouchUpInside];
        [self addSubnode:_deleteNode];
    }
    return self;
}

- (instancetype)initWithAsset:(AVURLAsset *)asset editMode:(BOOL)editMode {
    self = [super init];
    if (self != nil) {
        _imageNode = [[ASImageNode alloc] init];
        _imageNode.image = [asset getThumbnailImage];
        [self addSubnode:_imageNode];
        
        _deleteNode = [[ASImageNode alloc] init];
        _deleteNode.image = [UIImage imageNamed:@"delete"];
        _deleteNode.hidden = !editMode;
        [_deleteNode addTarget:self action:@selector(deleteAction) forControlEvents:ASControlNodeEventTouchUpInside];
        [self addSubnode:_deleteNode];
        
        _playNode = [[ASImageNode alloc] init];
        _playNode.image = [UIImage imageNamed:@"play_btn"];
        [_imageNode addSubnode:_playNode];

    }
    return self;
}

- (void)deleteAction {
    if(self.deleteBlock) {
        _deleteBlock(self.indexPath);
    }
}

- (ASLayoutSpec *)layoutSpecThatFits:(ASSizeRange)constrainedSize
{
    _deleteNode.style.preferredSize = CGSizeMake(20, 20);
    
    if(_playNode) {
        _playNode.frame = CGRectMake(constrainedSize.max.width - 5 - 10- 20, constrainedSize.max.width - 5 - 20, 20, 20);
    }

    ASInsetLayoutSpec *imageSepc = [ASInsetLayoutSpec insetLayoutSpecWithInsets:UIEdgeInsetsMake(0, 5, 0, 5) child:_imageNode];
    ASRelativeLayoutSpec *deleteSpec = [ASRelativeLayoutSpec relativePositionLayoutSpecWithHorizontalPosition:ASRelativeLayoutSpecPositionEnd verticalPosition:ASRelativeLayoutSpecPositionStart sizingOption:ASRelativeLayoutSpecSizingOptionDefault child:_deleteNode];
    
//    spec = [ASBackgroundLayoutSpec backgroundLayoutSpecWithChild:spec background:_backgroundImageNode];

    return [ASBackgroundLayoutSpec backgroundLayoutSpecWithChild:deleteSpec background:imageSepc];
}

- (void)setImage:(UIImage *)image
{
    _imageNode.image = image;
}

- (UIImage *)image
{
    return _imageNode.image;
}


@end
